package com.hgyc.mom.tool.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.hgyc.mom.common.print.PrintElementType;
import com.hgyc.mom.common.print.PrintTemplateDataField;
import com.hgyc.mom.common.print.PrintTemplateDataVO;
import com.hgyc.mom.common.util.http.HttpUtils;
import com.hgyc.mom.common.util.sign.Md5Utils;
import com.hgyc.mom.tool.vo.PrintRequestVO;
import com.hgyc.mom.tool.vo.TemplateDataVO;
import jakarta.servlet.http.HttpServletResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;
import com.hgyc.mom.tool.entity.PrintTemplate;
import com.hgyc.mom.tool.vo.PrintTemplateParam;
import com.hgyc.mom.tool.service.PrintTemplateService;
import com.hgyc.mom.common.vo.Result;
import com.hgyc.mom.common.util.poi.ExcelUtil;

import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 标签打印模板Controller
 *
 * @author fwj
 * @since 2025-07-14
 */
@Tag(name = "标签打印模板控制器", description = "标签打印模板控制器")
@RestController
@RequestMapping("/tool/print/template")
public class PrintTemplateController {
    @Autowired
    private PrintTemplateService printTemplateService;

    @Operation(summary = "查询标签打印模板列表", description = "查询标签打印模板列表")
    @PostMapping("/pageList")
    public Result<IPage<PrintTemplate>> pageList(@Parameter(description = "查询参数") @RequestBody PrintTemplateParam printTemplateParam) {
        Page<PrintTemplate> page = new Page<>(printTemplateParam.getPage(), printTemplateParam.getPageSize());
        PrintTemplate printTemplate = new PrintTemplate();
        BeanUtils.copyProperties(printTemplateParam, printTemplate);
        QueryWrapper<PrintTemplate> wrapper = QueryWrapperUtil.build(printTemplate);
        IPage<PrintTemplate> list = printTemplateService.page(page, wrapper);
        return Result.success(list);
    }

    @Operation(summary = "获取打印模板下拉数据", description = "获取打印模板下拉数据")
    @GetMapping("/selectList")
    public Result<List<PrintTemplate>> selectList() {
        return Result.success(printTemplateService.list());
    }

    @Operation(summary = "获取标签打印模板详细信息", description = "获取标签打印模板详细信息")
    @GetMapping(value = "/{id}")
    public Result getInfo(@Parameter(description = "标签打印模板ID") @PathVariable("id") Long id) {
        return Result.success(printTemplateService.getById(id));
    }
    @Operation(summary = "新增标签打印模板", description = "新增标签打印模板")
    @PostMapping
    public Result<?> save(@Parameter(description = "标签打印模板") @RequestBody PrintTemplate printTemplate) {
        if (printTemplate.getTemplateFile() != null) {
            byte[] data = printTemplate.getTemplateFile();

            String checkSum = Md5Utils.computeChecksum(data);
            String rawSum = printTemplate.getCheckSum();
            assert checkSum != null;
            if(!checkSum.equals(rawSum)){
                printTemplate.setCheckSum(checkSum);
            }
        }
        printTemplateService.saveTemplate(printTemplate);
        return Result.success();
    }

    @Operation(summary = "修改标签打印模板", description = "修改标签打印模板")
    @PutMapping
    public Result<?> update(@Parameter(description = "标签打印模板") @RequestBody PrintTemplate printTemplate) {
        if (printTemplate.getTemplateFile() != null) {
            byte[] data = printTemplate.getTemplateFile();

            String checkSum = Md5Utils.computeChecksum(data);
            String rawSum = printTemplate.getCheckSum();
            if(!checkSum.equals(rawSum)){
                printTemplate.setCheckSum(checkSum);
            }
        }
        printTemplateService.updateTemplate(printTemplate);
        return Result.success();
    }

    @Operation(summary = "删除标签打印模板", description = "删除标签打印模板")
    @DeleteMapping
    public Result<?> remove(@Parameter(description = "删除ID") @RequestParam("ids") Long[] ids) {
        return Result.success(printTemplateService.removeByIds(Arrays.asList(ids)));
    }

    @GetMapping("/dataSource")
    public Result<List<PrintTemplateDataVO>> getTemplateDataSource() {
        List<PrintTemplateDataVO> fieldList = printTemplateService.getTemplateDataSource();
        return Result.success(fieldList);
    }

    @Operation(summary = "标签打印", description = "标签打印")
    @PostMapping("/print")
    public Result<TemplateDataVO> print(@RequestBody PrintRequestVO printRequestVO) {
        TemplateDataVO templateDataVO = printTemplateService.print(printRequestVO);
        return Result.success(templateDataVO);
    }

    @Operation(summary = "模板设计", description = "铭牌模板设计")
    @GetMapping("/design/{id}")
    public Result<TemplateDataVO> design(@PathVariable("id") Long id) {
        TemplateDataVO templateDataVO = printTemplateService.design(id);
        return Result.success(templateDataVO);
    }

    @RequestMapping(value = "/download/{id}",method = RequestMethod.GET)
    public void download(@PathVariable Long id, HttpServletResponse response) throws UnsupportedEncodingException {
        PrintTemplate printTemplate = printTemplateService.getById(id);
        byte[] data = printTemplate.getTemplateFile();
        String fileName = java.net.URLEncoder.encode(printTemplate.getTemplateFileName(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        HttpUtils.writeData(response, data, "application/octet-stream");
    }

    @Operation(summary = "获取物料打印模板", description = "获取物料打印模板")
    @GetMapping("/material/template/{materialId}")
    public Result<List<PrintTemplate>> getMaterialTemplate(@PathVariable("materialId") Long materialId) {
        List<PrintTemplate> nameplateList= printTemplateService.getMaterialTemplate(materialId);
        return Result.success(nameplateList);
    }

    @GetMapping("/field/{templateId}")
    public Result getFieldByTemplate(@PathVariable("templateId") Long templateId) {
        List<PrintElementType> fieldList = printTemplateService.getFieldByTemplate(templateId);
        return Result.success(fieldList);
    }

    @GetMapping("/designer/json/{templateId}")
    public Result<String> getPrintTemplateJson(@PathVariable("templateId") Long templateId) {
        PrintTemplate printTemplate = printTemplateService.getById(templateId);
        return Result.success(printTemplate.getTemplateJson());
    }

    @PostMapping("/hiprint")
    public Result saveDesigner(@RequestBody PrintTemplate printTemplate) {
        printTemplateService.saveHiPrint(printTemplate);
        return Result.success("保存模板成功！");
    }
}
